const http = require('http')
const fs = require('fs')
const path = require('path')
const url = require('url')

const { getMime, getFileMime } = require('./module/common')

http.createServer((req, res) => {
  // 实现路由功能
  let pathname = url.parse(req.url).pathname 
  pathname = pathname=='/' ? '/index.html' : pathname;
  let extname = path.extname(pathname)
  if(pathname !== '/favicon.ico') {
    fs.readFile('./static' + pathname, async (err, data) => {
      if(err) {
        res.writeHead(404, {"Content-Type": "text/html;charset=utf-8"})
        res.end('404 页面不存在')
      }else {
        let mime = await getFileMime(extname)
        res.writeHead(200, {"Content-Type": `${mime};charset=utf-8`})
        res.end(data)
      }
    })
  }
}).listen(3000)

console.log('服务器在3000端口运行...')